<template>
	<div>
		<Card :bstocked="false" dis-hover class="mt15">
			<Form ref="listData" :model="listData" :label-width="labelWidth" :label-position="labelPosition"
				class="tabform" @submit.native.prevent>
				<div class="acea-row">

					<FormItem label="文件名">
						<Input v-model="listData.title" placeholder="输入文件名" element-id="name" clearable
							style="width:250px;">
						</Input>
					</FormItem>

					<Button type="primary" @click="userSearchs" class="ml20">{{$t('page.stock.search')}}</Button>
					<Button @click="reset" class="ml20">{{$t('page.stock.reset')}}</Button>
				</div>
			</Form>
		</Card>
		<Card :bordered="false" dis-hover class="mt15">
			<Button type="primary" @click="fileAdd">添加文件</Button>
			<vxe-table bstock="inner" ref="xTable" class="mt25" :loading="loading" row-id="id"
				:expand-config="{accordion: true}" :checkbox-config="{reserve: true}" @checkbox-all="checkboxAll"
				@checkbox-change="checkboxItem" :data="helpCenterList" v-if="tabType != 1">
				<vxe-column field="id" title="ID" min-width="75" align="left" fixed="left"></vxe-column>
				<vxe-column field="title" title="标题" min-width="330" align="left" fixed="left"></vxe-column>
				<vxe-column field="url" title="文件路径" min-width="430" align="left" fixed="left"></vxe-column>

				<vxe-column field="format" title="文件类型" min-width="100"></vxe-column>
				<vxe-column field="size" title="文件大小" min-width="100"></vxe-column>
				<!-- <vxe-column field="created_at" title="上传时间" min-width="150"></vxe-column> -->
				<vxe-column field="created_at" title="上传时间" min-width="150" :formatter="formatDateTime"></vxe-column>
				<vxe-column field="action" title="操作" align="center" min-width="200" fixed="right">
				  <template v-slot="{ row,index }">
				    <a @click="del(row,'删除该文件',index)">删除</a>
				  </template>
				</vxe-column>
			</vxe-table>
			<div class="acea-row row-right mt15">
				<Page :total="total" :current="listData.page" @on-change="pageChange" :page-size="listData.limit" />
			</div>
		</Card>
		<file-from :formValidate="formValidate" @getList="userSearchs"  ref="fileFrom"></file-from>
	</div>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import fileFrom from "../components/fileFrom";
	import {
		getNoPageSupplierProductList
	} from "@/api/supplier";
	// import userDetails from "@/components/userDetails/userDetails";
	import Setting from "@/setting";
	import {
		helpCenterList,
		exportStockList,
		stockHistoryList,
		exportStockHistoryList
	} from "@api/stock";
	import {
		helpCenterDelete,
	} from "@api/product";
	export default {
		name: "index",
		components: {
			fileFrom
			// userDetails,
		},
		data() {
			return {
				isAll: 0,
				stockNameList: [{
					value: '1791498718751334401',
					label: 'CA5005'
				}, {
					value: '101816795504',
					label: 'Houston'
				}],
				supplierList: [],
				isCheckBox: false,
				timeVal: "",
				checkUidList: [],
				formValidate: {},
				// 订单列表
				listData: {
					page: 1,
					limit: 10,
					type: "",
					status: "",
					data: "",
					real_name: "",
					warehouse_name: "",
					code: "",
					supplier_id: "",
					title:'',
					sku: "",
					pay_type: "",
					stock_type: "0",
					field_key: "all",
					tab_type: 0,
				},
				helpCenterList: [],
				stockHistoryList: [],
				total: 0,
				loading: false,
				tabType: 0,
			};
		},
		watch: {
			$route() {
				if (this.$route.fullPath === `${Setting.roterPre}/stock/list?type=7&status=1`) {
					this.getPath();
				}
			}
		},
		computed: {
			...mapState("store/layout", ["isMobile"]),
			labelWidth() {
				return this.isMobile ? undefined : 80;
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
			stockSkuList() {
				return [{
					value: '0',
					label: $t('page.stock.all_sku')
				}, {
					value: '1',
					label: $t('page.stock.in_stock')
				}, {
					value: '3',
					label: $t('page.stock.show_low_sku')
				}, {
					value: '4',
					label: $t('page.stock.zero_sku')
				}]
			}
		},
		created() {
			if (this.$route.fullPath === `${Setting.roterPre}/stock/list?type=7&status=1`) {
				this.getPath();
			} else {
				this.getList();
			}
		},
		mounted() {
			this.getSupplierList();
		},
		methods: {
			// 删除
			del (row, tit, num) {
			  let delfromData = {
			      title: tit,
			      num: num,
			      url: `help_center/delHelpCenterFile/${row.id}`,
			      method: 'DELETE',
			      ids: ''
			  };
			  this.$modalSure(delfromData).then((res) => {
			      this.helpCenterList.splice(num,1);
			      this.$Message.success(res.msg);
				  this.userSearchs();
			  }).catch(res => {
			      this.$Message.error(res.msg);
			  });
			},
			fileAdd() {
				this.$refs.fileFrom.modals = true;
				this.$refs.fileFrom.titleFrom = "添加文件";
				this.formValidate = {
					sort: 0,
				};
				this.formValidate.fid = [0];
				this.formValidate.is_show = 1;
				this.$refs.menusFrom.type = 1;
			},
			formatDateTime({
				cellValue
			}) {
				if (!cellValue) return '';

				// 方法1: 使用原生 Date 对象
				const date = new Date(cellValue);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;

				// 方法2: 使用字符串分割（如果格式固定）
				// return cellValue.replace('T', ' ').substring(0, 16);

				// 方法3: 使用 day.js（如果项目中已安装）
				// return dayjs(cellValue).format('YYYY-MM-DD HH:mm');
			},
			reset() {
				this.timeVal = ""
				this.listData = {
					page: 1,
					limit: 10,
					type: "",
					status: "",
					data: "",
					title:"",
					real_name: "",
					warehouse_name: "",
					code: "",
					sku: "",
					pay_type: "",
					stock_type: "0",
					field_key: "all",
					tab_type: 0,
				};
	
				this.getList();
			},
			// 列格式化函数
			formatDateColumn({
				cellValue
			}) {
				const date = new Date(cellValue);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},

			//跳转刷新
			getPath() {
				this.listData.page = 1;
				this.listData.status = this.$route.query.status;
				this.getList();
			},
			allReset() {
				this.isAll = 0;
				this.isCheckBox = false;
				this.$refs.xTable.setAllCheckboxRow(false);
				this.checkUidList = [];
			},
			checkboxItem(e) {
				let id = parseInt(e.rowid);
				let index = this.checkUidList.indexOf(id);
				if (index !== -1) {
					this.checkUidList = this.checkUidList.filter((item) => item !== id);
				} else {
					this.checkUidList.push(id);
				}
			},
			checkboxAll() {
				// 获取选中当前值
				let obj2 = this.$refs.xTable.getCheckboxRecords(true);
				// 获取之前选中值
				let obj = this.$refs.xTable.getCheckboxReserveRecords(true);
				if (this.isAll == 0 && this.checkUidList.length <= obj.length && !this.isCheckBox) {
					obj = [];
				}
				obj = obj.concat(obj2);
				let ids = [];
				obj.forEach((item) => {
					ids.push(parseInt(item.id))
				})
				this.checkUidList = ids;
				if (!obj2.length) {
					this.isCheckBox = false;
				}
			},

			getHistoryList() {
				this.loading = true;
				stockHistoryList(this.listData).then(res => {
					let data = res.data;
					this.$set(this, 'stockHistoryList', data.list);
					this.total = res.data.count;
					this.loading = false;
				}).catch(err => {
					this.loading = false;
					this.$Message.error(err.msg)
				})
			},
			getList() {
				this.loading = true;
				helpCenterList(this.listData).then(res => {
					let data = res.data;
					this.$set(this, 'helpCenterList', data.list);
					this.total = res.data.count;
					this.loading = false;
				}).catch(err => {
					this.loading = false;
					this.$Message.error(err.msg)
				})
			},
			pageChange(index) {
				this.listData.page = index;
				if (this.tabType != 1) {
					//库存列表
					this.getList();
				} else {
					//历史库存列表
					this.getHistoryList();
				}
			},
			userSearchs() {
				this.getList();
			},
			async exportStock() {
				try {
					this.exportLoading = true;
					let res; // 在函数作用域声明
					// 1. 调用导出接口获取文件信息
					if (this.tabType != 1) {
						res = await exportStockList(this.listData);
					} else {
						res = await exportStockHistoryList(this.listData);
						console.log("res111---------", res);
					}

					// 2. 检查响应是否成功
					if (res.code !== 0) {
						throw new Error(res.msg || '导出失败');
					}

					// 3. 获取文件信息
					const fileInfo = res.data;

					// 4. 使用文件URL下载文件
					await this.downloadFile(fileInfo);

					// 5. 显示成功消息
					Message.success('导出成功，文件已开始下载');

				} catch (error) {
					// 错误处理
					Message.error(error.message || '导出失败，请重试');
					console.error('导出错误:', error);
				} finally {
					this.exportLoading = false;
				}
			},
			async downloadFile(fileInfo) {
				try {
					// 1. 创建下载链接（优先使用 download_url，再使用 exports_url）
					// const downloadUrl = fileInfo.download_url || fileInfo.exports_url;
					const downloadUrl = fileInfo.exports_url;
					// 2. 创建隐藏的<a>标签触发下载
					const link = document.createElement('a');
					link.href = downloadUrl;

					// 从URL中提取文件名，或自定义文件名
					const fileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
					link.download = fileName; // 设置下载文件名

					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);

				} catch (error) {
					console.error('文件下载错误:', error);
					throw new Error('文件下载失败: ' + error.message);
				}
			},
			getFullUrl(url) {
				// 如果已经是完整URL，直接返回
				if (url.startsWith('http://') || url.startsWith('https://')) {
					return url;
				}

				// 处理Windows路径分隔符问题
				const cleanUrl = url.replace(/\\/g, '/');

				// 如果是绝对路径，直接返回（根据当前域名）
				if (cleanUrl.startsWith('/')) {
					return `${window.location.origin}${cleanUrl}`;
				}

				// 相对路径处理（基于当前页面）
				return `${window.location.origin}${window.location.pathname}/../${cleanUrl}`;
			}
		},
	};
</script>

<style lang="stylus" scoped>
	.tdinfo {
		margin-left: 75px;
		margin-top: 16px;
	}

	.expand-row {
		margin-bottom: 16px;
		font-size: 12px;
	}

	.tabBox {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;

		.tabBox_img {
			width: 30px;
			height: 30px;

			img {
				width: 100%;
				height: 100%;
			}
		}

		.tabBox_tit {
			width: 267px;
			height: 30px;
			line-height: 30px;
			font-size: 12px !important;
			margin: 0 2px 0 10px;
			letter-spacing: 1px;
			box-sizing: bstock-box;
		}
	}

	.tabBox+.tabBox {
		margin-top: 5px;
	}
</style>